import 'dart:math';

import 'package:card_swiper/card_swiper.dart';
import 'package:eplorex/models/HomeItemModel.dart';
import 'package:eplorex/pages/community/water_card_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

import '../../dao/home_feed_dao.dart';
import '../../models/moment/banner_model.dart';
import 'community_navigator.dart';
import 'search_bar.dart';

class CommunityPage extends StatefulWidget {
  @override
  State<CommunityPage> createState() => _CommunityPageState();
}

class _CommunityPageState extends State<CommunityPage> {
  List _waterFallList = [];
  Future<List<HomeItemModel>>? _fetchData;
  Future<List<BannerModel>>? _fetchBannerData;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _fetchData = HomeDao.fetch();
    _fetchBannerData = HomeDao.fetchBanner();
    var randomNum = new Random();

    for (var i = 0; i < 40; i++) {
      _waterFallList.add(240 + 150 * randomNum.nextDouble());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: SearchBarEnhance(),
        backgroundColor: Colors.white,
      ),
      body: ListView(
        children: [_getSwiper(), _getNavigator(), _getListView()],
      ),
      floatingActionButton: FloatingActionButton(
        shape: CircleBorder(),
        backgroundColor: Colors.blue,
        child: Icon(Icons.add,color: Colors.white,),
        onPressed: () {
          Navigator.pushNamed(context, '/moment/create',
              arguments: {"source": "home"});
        },
      ),
    );
  }

  Widget _getNavigator() {
    return Container(
      child: IndexNavigator(),
    );
  }

  Widget _getSwiper() {
    var height = MediaQuery.of(context).size.width / 350.0 * 180.0;
    return Container(
      height: height,
      margin: EdgeInsets.symmetric(horizontal: 5),
      clipBehavior: Clip.antiAlias,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8),
      ),
      child: FutureBuilder(
        future: _fetchBannerData,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting ||
              snapshot.data == null) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }

          return Swiper(
            itemBuilder: (BuildContext context, int index) {
              return Image.network(
                (snapshot?.data as List)[index].url,
                fit: BoxFit.fill,
              );
            },
            autoplay: true,
            itemCount: snapshot?.data.length,
            pagination: SwiperPagination(),
            // control: SwiperControl(),
          );
        },
      ),
    );
  }

  Widget _getListView() {
    return Container(
      padding: EdgeInsets.all(10),
      child: FutureBuilder(
        future: _fetchData,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting ||
              snapshot?.data == null) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          }
          double width= (MediaQuery.of(context).size.width-30)/2;
          return MasonryGridView.count(
            // 展示几列
            crossAxisCount: 2,
            // 元素总个数
            itemCount: snapshot?.data.length,
            // 单个子元素
            itemBuilder: (BuildContext context, int index) {
              HomeItemModel homeItemModel=  snapshot.data[index];

              // var height= homeItemModel?.imageHeight> 0 ? homeItemModel.imageHeight : _waterFallList[index];
              return WaterCardWidget(item: snapshot.data[index], height: _waterFallList[index],);
            },
            // 纵向元素间距
            mainAxisSpacing: 10,
            // 横向元素间距
            crossAxisSpacing: 10,
            //本身不滚动，让外面的singlescrollview来滚动
            physics: const NeverScrollableScrollPhysics(),
            shrinkWrap: true, //收缩，让元素宽度自适应
          );
        },
      ),
    );
  }

}
